package session1.examples;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Eg2 {
    public static void main(String[] args) {
        try{
            main();
        }
        catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
    static void main()throws Exception {
        int size=100;
        AddOneThread[] threads=new AddOneThread[size];
        Account account;
        for (int j=0;j<5;j++) {
            account=new Account(0);
            for (int i = 0; i < size; i++)
                threads[i] = new AddOneThread(
                    "Timer No."+i, account);
            for (int i = 0; i < size; i++) {
                threads[i].start();
            }
            Thread.sleep(200);
            System.out.println("\t\t\tsum=" + account.getBalance());
        }
    }
}
class AddOneThread extends Thread{
    public AddOneThread(String name, Account account) {
        super(name);
        this.account = account;
    }
    public AddOneThread(Account account) {
        this.account = account;
    //    start();
    }
    final Account account;
    @Override
    public void run() {
        synchronized (System.out){
            try {
                //    System.out.println(Thread.currentThread().getName());
                Thread.sleep(1);
            } catch (InterruptedException interruptedException) {
                System.out.println("Thread:");
                System.out.println(interruptedException.getMessage());
            }
            account.addOne();
        }
    }

}
class Account{
    private int balance;
    Lock lock;
    public Account(int balance) {
        this.balance = balance;
        this.lock= new ReentrantLock(true);
    }
    public void addOne(){
        lock.lock();
        balance++;
        lock.unlock();
    }
    public void resetAccount(){balance=0;}
    public int getBalance() {return balance;}
    @Override
    public String toString() {
        return getBalance()+super.toString();
    }
}